package cn.fastoo.task;

import cn.fastoo.common.cache.Price;
import cn.fastoo.common.dao.SmsrecordDao;
import cn.fastoo.common.entity.Smsrecord;
import cn.fastoo.common.utils.MessageHelper;
import cn.fastoo.common.utils.PhoneNumberUtils;
import cn.fastoo.common.utils.PriceUtil;
import cn.fastoo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Save Queue
 */
public class SaveMtMessageQueue {

    private final static Logger logger = LoggerFactory.getLogger(SaveMtMessageQueue.class);

    private static JdbcTemplate jt;
    private static SmsrecordDao smsrecordDao;
    private static UserService userService;

    private static BlockingQueue<MtMessage> blockingQueue = new LinkedBlockingQueue<MtMessage>();

    private static Long UPDATE_INTERVAL = 200L;

    static {
        Consumer consumer=new Consumer(blockingQueue);

        new Thread(consumer,"save_queue").start();

    }

    public static void put(JdbcTemplate jdbcTemplate,SmsrecordDao recordDao,UserService userBaseService,MtMessage mtMessage){

        try {
            jt = jdbcTemplate;
            smsrecordDao = recordDao;
            userService = userBaseService;
            blockingQueue.put(mtMessage);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //消费者
    public static class Consumer implements Runnable {

        private final BlockingQueue<MtMessage> blockingQueue;

        private volatile boolean flag;

        public Consumer(BlockingQueue<MtMessage> blockingQueue) {
            this.blockingQueue = blockingQueue;
        }
        public void run() {
            while(!flag){

                try {
                    MtMessage mtMessage = blockingQueue.take();
                    //保存批次发送记录
                    String das = mtMessage.getDas();
                    String[] dasArr = das.split(",");
                    if (dasArr != null && dasArr.length > 0) {
                        for (String da : dasArr) {
                            String contryCode = PhoneNumberUtils.getCountryCode(da);
                            //短信计费条数
                            Integer smsize = MessageHelper.getSmsLength(mtMessage.getMsg(),contryCode,mtMessage.getSignName());
                            Price price = PriceUtil.load(jt, mtMessage.getApiKey(), contryCode);

                            Smsrecord smsrecord = new Smsrecord();
                            smsrecord.setLocalMsgid(MessageHelper.getSequenceId(new Date().getTime()));
                            smsrecord.setLoginName(mtMessage.getLoginName());
                            smsrecord.setMsgContent(mtMessage.getMsg());
                            smsrecord.setApiKey(mtMessage.getApiKey());
                            smsrecord.setBatchId(mtMessage.getBatchId());
                            smsrecord.setDestAddr(da);
                            smsrecord.setCountryCode(contryCode);
                            smsrecord.setPrice(price.getMtPrice());
                            smsrecord.setFeeCount(smsize);
                            if ("CN".equals(contryCode)) {
                                smsrecord.setIsAudit(0);
                            }else{
                                smsrecord.setIsAudit(1);
                            }

                            smsrecordDao.insert(smsrecord);

                            //定时的计划不发送
                            if (StringUtils.isBlank(mtMessage.getTiming())&&!"CN".equals(contryCode)) {
                                MtMessage mt = new MtMessage();
                                mt.setDa(da);
                                mt.setMsg(mtMessage.getMsg());
                                mt.setLocalMsgid(smsrecord.getLocalMsgid());
                                mt.setSignName(mtMessage.getSignName());
                                mt.setApiKey(mtMessage.getApiKey());
                                mt.setUserBaseId(mtMessage.getUserBaseId());
                                FastooMtMessageQueue.put(userService,mt);
                                logger.info("end save");
                            }

                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        public void shutDown(){
            flag=true;
        }
    }





    public static void main(String[] args) throws InterruptedException {

        MtMessage mtMessage = new MtMessage();
        mtMessage.setUserBaseId(4L);
        mtMessage.setBatchId(1L);
        mtMessage.setLoginName("15711586282");
        mtMessage.setDas("85267643495");
        mtMessage.setMsg("Illcomming");
        mtMessage.setTiming(null);
        mtMessage.setSignName("");
        mtMessage.setApiKey("a47dd09338834deda2e0e717a90e2cce");

//        SaveMtMessageQueue.put(mtMessage);
        MtMessage mtMessage2 = new MtMessage();
        mtMessage2.setUserBaseId(4L);
        mtMessage2.setBatchId(1L);
        mtMessage2.setLoginName("15711586282");
        mtMessage2.setDas("85267643495");
        mtMessage2.setMsg("Illcomming2");
        mtMessage2.setTiming(null);
        mtMessage2.setSignName("");
        mtMessage2.setApiKey("a47dd09338834deda2e0e717a90e2cce");

//        SaveMtMessageQueue.put(mtMessage2);

    }
}
